﻿//https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475?tpId=196&tqId=37176&ru=/exam/oj
class Solution
{
public:
	string solve(string s, string t)
	{
		string ret;
		int tmp = 0; // 进位 + 本次累加和
		int i = s.size() - 1, j = t.size() - 1;
		while (i >= 0 || j >= 0 || tmp) // 模拟加法
		{
			if (i >= 0) tmp += s[i--] - '0';
			if (j >= 0) tmp += t[j--] - '0';
			ret += '0' + tmp % 10;
			tmp /= 10;
		}
		reverse(ret.begin(), ret.end()); // 别忘逆序
		return ret;
	}
};


//https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=196&tqId=37147&ru=/exam/oj

class Solution {
public:
    // 逆序链表
    ListNode* reverse(ListNode* head) {
        ListNode* newHead = new ListNode(0);
        ListNode* cur = head;
        while (cur) {
            ListNode* next = cur->next;
            cur->next = newHead->next;
            newHead->next = cur;
            cur = next;
        }
        cur = newHead->next;
        delete newHead;
        return cur;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // 1. 逆序
        head1 = reverse(head1);
        head2 = reverse(head2);
        // 2. ⾼精度加法
        int t = 0;
        ListNode* cur1 = head1, * cur2 = head2;
        ListNode* ret = new ListNode(0);
        ListNode* prev = ret;
        while (cur1 || cur2 || t) {
            if (cur1) {
                t += cur1->val;
                cur1 = cur1->next;
            }
            if (cur2) {
                t += cur2->val;
                cur2 = cur2->next;
            }
            prev = prev->next = new ListNode(t % 10);
            t /= 10;
        }
        cur1 = ret->next;
        ret->next = nullptr;
        delete ret;
        return reverse(cur1);
    }
};


//https://www.nowcoder.com/practice/c4c488d4d40d4c4e9824c3650f7d5571?tpId=196&tqId=37177&ru=/exam/oj

class Solution
{
public:
    string solve(string s, string t)
    {
        reverse(s.begin(), s.end());
        reverse(t.begin(), t.end());
        int m = s.size(), n = t.size();
        vector<int> tmp(m + n);
        // 1. ⽆进位相乘相加
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                tmp[i + j] += (s[i] - '0') * (t[j] - '0');
            }
        }
        // 2. 处理进位
        int c = 0;
        string ret;
        for (auto x : tmp)
        {
            c += x;
            ret += c % 10 + '0';
            c /= 10;
        }
        while (c)
        {
            ret += c % 10 + '0';
            c /= 10;
        }
        // 3. 处理前导零
        while (ret.size() > 1 && ret.back() == '0') ret.pop_back();
        reverse(ret.begin(), ret.end());
        return ret;
    }
};